package algotithm.leetcode.dp.test368;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 25068
 * @Date 2021/4/23 9:41
 * @Title 368. 最大整除子集
 */
public class Solution {


    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = {1,2,3};
        List<Integer> integers = solution.largestDivisibleSubset(nums);
        System.out.println(integers);
    }

    public List<Integer> largestDivisibleSubset(int[] nums) {
        int len = nums.length;
        int[] dp = new int[len];
        Arrays.fill(dp,1);
        Arrays.sort(nums);
        int maxValue = dp[0];
        int maxSize = 1;
        for (int i = 1; i < len; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[i] % nums[j] == 0) {
                    dp[i] = Math.max(dp[i],dp[j] + 1);
                }
            }
            if (dp[i] > maxSize) {
                maxValue = nums[i];
                maxSize = dp[i];
            }
        }
        List<Integer> res = new ArrayList<>();
        if (maxSize == 1) {
            res.add(nums[0]);
            return res;
        }
        for (int i = len - 1; i >= 0 && maxSize >= 0; i--) {
            if (maxValue % nums[i] == 0 && dp[i] == maxSize) {
                res.add(nums[i]);
                maxValue = nums[i];
                maxSize--;
            }
        }
        return res;
    }

}
